package com.yonyou.mm.controller;

import com.yonyou.mm.aop.ControllerLog;
import com.yonyou.mm.aop.LogUtil;
import com.yonyou.mm.params.ParamsEngine;
import com.yonyou.mm.service.ComplexBusinessService;
import com.yonyou.mm.service.TransferService;
import com.yonyou.mm.util.ConstUtil;
import com.yonyou.mm.util.ExceptionUtils4DxyWeb;
import com.yonyou.mm.util.RequestResultDealUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yijx on 2017/3/23.
 */
@Controller
public class LoginController {

    @RequestMapping(value = {"/","/Login"})
    public String index() {
        return "Login";
    }


    @RequestMapping(value = "/WorkTask")
    public String transferPage() {
        return "WorkTask";
    }
    
    @RequestMapping(value = "/WorkTask2")
    public String transferPage2() {
        return "WorkTask2";
    }

    @RequestMapping(value = "/WareHouse")
    public String wareHousePage() {
        return "WareHouse";
    }
    
    @RequestMapping(value = "/WareHousePickm")
    public String wareHousePickmPage() {
        return "WareHousePickm";
    }

    /**
     * 管理员登录，配置NC地址、数据源等信息
     * 前台参数：ConstUtil.USERTYPE,USERNAME,PASSWORD
     * @param request
     * @param response
     * @param paramData
     */
    @RequestMapping(value = "/logining")
    @ControllerLog(remark = "登录")
    public void adminLogin(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String, Object> paramData,Model model){
        HttpSession session = request.getSession();
        TransferService configutilservice = new TransferService();
        //处理登录请求
        boolean isLogin = configutilservice.isLogin(paramData,session);
        JSONObject obj = new JSONObject();
        if (isLogin) {
            String  userType = (String) paramData.get(ConstUtil.USERTYPE);
            session.setAttribute(ConstUtil.USERTYPE,userType);
            session.setAttribute(ConstUtil.USERNAME, paramData.get(ConstUtil.USERNAME));
            session.setAttribute(ConstUtil.PASSWORD, paramData.get(ConstUtil.PASSWORD));
            String dbname = ParamsEngine.getXmlConfig().getString("TransferClient.ncdataresource");
            session.setAttribute(ConstUtil.DBSOURCE,dbname);
            //mes登录信息
            session.setAttribute(ConstUtil.MES_USERNAME, paramData.get(ConstUtil.USERNAME));
            session.setAttribute(ConstUtil.MES_PASSWORD, paramData.get(ConstUtil.PASSWORD));
            String mesds = ParamsEngine.getXmlConfig().getString("TransferClient.mesdataresource");
            session.setAttribute(ConstUtil.MES_DBSOURCE,mesds);
            obj.put("flag",1);
        } else {
            obj.put("flag", 0);
        }
        try {
            PrintWriter pw = response.getWriter();
            pw.write(obj.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    @RequestMapping(value = { "/SaveConfig" })
    @ControllerLog(remark = "保存系统配置")
    public void SaveConfig(HttpServletResponse response, @RequestParam Map<Object, Object> obj) {
        // 修改variableConfig.xml的配置文件
        TransferService configutilservice = new TransferService();
        configutilservice.saveConfig(obj);
        JSONObject objRet = new JSONObject();
        objRet.put("flag", 0);
        try {
            PrintWriter pw = response.getWriter();
            pw.write(objRet.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    /**
     * 将仓库信息存入Session
     * 前台参数：ConstUtil.ORG，ORGNAME,WAREHOUSE,WAREHOUSENAME,POSITION,POSITIONNAME
     * @param request
     * @param response
     */
    @RequestMapping(value = "/positionToSession")
    @ControllerLog(remark = "保存站点信息到Session")
    public void positionToSession(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();
        String org = request.getParameter(ConstUtil.ORG);
        String provpos=request.getParameter(ConstUtil.PROVPOS);
        String position= request.getParameter(ConstUtil.POSITION);
        String orgName = request.getParameter(ConstUtil.ORGNAME);
        String warehouseName=request.getParameter(ConstUtil.WAREHOUSENAME);
        String positionName=request.getParameter(ConstUtil.POSITIONNAME);
        String destpos=request.getParameter(ConstUtil.DESTPOS);
        String warehouse = request.getParameter(ConstUtil.WAREHOUSE);       
        session.setAttribute(ConstUtil.ORG,org);
        session.setAttribute(ConstUtil.PROVPOS,provpos);
        session.setAttribute(ConstUtil.POSITION,position);
        session.setAttribute(ConstUtil.ORGNAME,orgName);
        session.setAttribute(ConstUtil.WAREHOUSENAME,warehouseName);
        session.setAttribute(ConstUtil.POSITIONNAME,positionName);
        session.setAttribute(ConstUtil.DESTPOS,destpos);
        session.setAttribute(ConstUtil.WAREHOUSE,warehouse);
        JSONObject objRet = new JSONObject();
        objRet.put("flag", 0);
        objRet.put(ConstUtil.USERTYPE,session.getAttribute(ConstUtil.USERTYPE));
        try {
            PrintWriter pw = response.getWriter();
            pw.write(objRet.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    @RequestMapping(value = { "/LinkNC" })
    @ControllerLog(remark = "测试NC连接")
    public void LinkNC(HttpServletRequest request, HttpServletResponse response) {
        // 是否连通
        TransferService configutilservice = new TransferService();
        //实际上通过登录测试是否连接
        boolean isLinkNC = configutilservice.isLinkNC();
        JSONObject obj = new JSONObject();
        if (isLinkNC) {
            obj.put("flag", 0);
        } else {
            obj.put("flag", 1);
        }
        try {
            PrintWriter pw = response.getWriter();
            pw.write(obj.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }
    
    @RequestMapping(value = { "/LinkMES" })
    @ControllerLog(remark = "测试MES连接")
    public void LinkMES(HttpServletRequest request, HttpServletResponse response) {
        // 是否连通
        TransferService configutilservice = new TransferService();
        //实际上通过登录测试是否连接
        boolean isLinkMES = configutilservice.isLinkMES();
        JSONObject obj = new JSONObject();
        if (isLinkMES) {
            obj.put("flag", 0);
        } else {
            obj.put("flag", 1);
        }
        try {
            PrintWriter pw = response.getWriter();
            pw.write(obj.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    /**
     * 加载系统配置界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = { "/LoadAdminConfig" })
    @ControllerLog(remark = "加载系统配置")
    public String LoadConfig(HttpServletRequest request, Model model) {
        TransferService configutilservice = new TransferService();
        model = configutilservice.addAdminAttr(model);
        return "AdminConfig";
    }

    /**
     * 加载车间配置界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/LoadWorkerConfig")
    @ControllerLog(remark = "加载车间配置")
    public String LoadWorkTask(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        HashMap<String, Object> info = new HashMap<String, Object>();
        info.put(ConstUtil.USERNAME,session.getAttribute(ConstUtil.USERNAME));

        TransferService configutilservice = new TransferService();
        String val  = configutilservice.addWorkTaskAttr(info);
        model.addAttribute("config", JSONObject.fromObject(val));
        String usertype=(String) session.getAttribute(ConstUtil.USERTYPE);
        model.addAttribute("titleinfo","车间管理员配置");
        return "WorkerConfig";
    }
    
    /**
     * 加载仓库配置界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/LoadWareHouseConfig")
    @ControllerLog(remark = "加载仓库配置")
    public String LoadWareHouseTask(HttpServletRequest request, Model model){
        HttpSession session = request.getSession();
        HashMap<String, Object> info = new HashMap<String, Object>();
        info.put(ConstUtil.USERNAME,session.getAttribute(ConstUtil.USERNAME));

        TransferService configutilservice = new TransferService();
        String val  = configutilservice.addWorkTaskAttr(info);
        model.addAttribute("config", JSONObject.fromObject(val));
        String usertype=(String) session.getAttribute(ConstUtil.USERTYPE);
        model.addAttribute("titleinfo","仓库管理员配置");
        return "WareHouseConfig";
    }

    /**
     * 查询仓库
     * 前台参数：无
     * 传NC参数：默认参数，ConstUtil.TASKTYPE
     * NC回传：仓库id,仓库名称
     * @param request
     * @param response
     */
    @RequestMapping(value = "/searchWarehouse")
    @ControllerLog(remark = "查询仓库")
    public void searchWH(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        JSONObject info = new JSONObject();
        info.put(ConstUtil.TASKTYPE,"searchWarehouse");
        info.put(ConstUtil.ORG,request.getParameter(ConstUtil.ORG));
        JSONObject result = TransferService.requestService(info,session);
        JSONArray warehouses = new JSONArray();
        if(result.containsKey("data") && result.get("data") instanceof JSONArray) {
            warehouses= result.getJSONArray("data");
        }
//        warehouses = JSONArray.fromObject(TestData.warehouses);
        try {
            PrintWriter pw = response.getWriter();
            pw.write(warehouses.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

    /**
     * 查询站点
     * 前台参数：ConstUtil.WAREHOUSE
     * 传NC参数：默认参数，WAREHOUSE
     * MES回传：站点id,站点名称
     * @param request
     * @param response
     */
    @RequestMapping(value = "/searchPosition")
    @ControllerLog(remark = "查询站点")
    public void searchPosition(HttpServletRequest request, HttpServletResponse response){

		JSONObject param = new JSONObject();
		param.put(ConstUtil.ORG,request.getParameter(ConstUtil.ORG));
		HttpSession session = request.getSession();
		try {
			JSONObject result = ComplexBusinessService
					.queryWorkCenterByStordoc(param, session);
			JSONArray positions = new JSONArray();
			if (result.containsKey("datas")
					&& result.get("datas") instanceof JSONArray) {
				positions = result.getJSONArray("datas");
			}
			try {
				PrintWriter pw = response.getWriter();
				pw.write(positions.toString());
			} catch (IOException e) {
				ExceptionUtils4DxyWeb.dealException(e);
			}
        } catch (Exception e) {
        	RequestResultDealUtil.returnResult(response, "1", e, null);
        }
    }
    
    /**
     * 查询暂存区
     * 前台参数：ConstUtil.POSITION
     * 传NC参数：默认参数，POSITION
     * NC回传：暂存区id
     * @param request
     * @param response
     */
    @RequestMapping(value = "/searchDespost")
    @ControllerLog(remark = "查询暂存区")
    public void searchDestpos(HttpServletRequest request, HttpServletResponse response){

		JSONObject param = new JSONObject();
		param.put(ConstUtil.POSITION,request.getParameter(ConstUtil.POSITION));
		HttpSession session = request.getSession();
		try {
			JSONObject result = ComplexBusinessService
					.queryDestposByWk(param, session);
			JSONArray destposes = new JSONArray();
			if (result.containsKey("datas")
					&& result.get("datas") instanceof JSONArray) {
				destposes = result.getJSONArray("datas");
			}
			try {
				PrintWriter pw = response.getWriter();
				pw.write(destposes.toString());
			} catch (IOException e) {
				ExceptionUtils4DxyWeb.dealException(e);
			}
        } catch (Exception e) {
        	RequestResultDealUtil.returnResult(response, "1", e, null);
        }
    }


    /**
     * 查询组织
     * 前台参数：无
     * 传NC参数：默认参数(ORG空)，ConstUtil.TASKTYPE
     * NC回传：组织id,组织名称
     * @param request
     * @param response
     */
    @RequestMapping(value = "/searchOrg")
    @ControllerLog(remark = "查询组织")
    public void searchOrg(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        JSONObject info = new JSONObject();
        info.put(ConstUtil.TASKTYPE,"searchOrg");
        JSONObject result = TransferService.requestService(info,session);
        JSONArray orgs = new JSONArray();
        if(result.containsKey("data") && result.get("data") instanceof JSONArray) {
             orgs= result.getJSONArray("data");
        }
//        orgs = JSONArray.fromObject(TestData.orgs);
        try {
            PrintWriter pw = response.getWriter();
            pw.write(orgs.toString());
        } catch (IOException e) {
        	ExceptionUtils4DxyWeb.dealException(e);
        }
    }

}
